#include <KFileDialog>
#include <KIO/NetAccess>
#include <KMessageBox>
#include <KSaveFile>
#include <QDebug>

#include "maincontrol.h"
#include "journalwindow.h"
#include "document.h"
#include "journaltabwidget.h"
#include <KActionCollection>

MainControl::MainControl(JournalWindow *p_window): QObject(p_window)
{
    m_window = p_window;
}

void MainControl::saveFileAs()
{
    saveFileAs(KFileDialog::getSaveFileName());
}

void MainControl::onWindowLoaded()
{
    // Create the pen-configurations.
    
    // When no Document has been opened via a parameter, open a new one.
    if (m_window->getTabWidget()->count() == 0) {
        newDocument();
    }
}

void MainControl::saveFile()
{
    // TODO: m_filename should be moved to current-document.
//    if (!m_fileName.isEmpty()) {
//        saveFileAs(m_fileName);

//    } else {
        saveFileAs();
//    }
}

void MainControl::closeDocument(int tab)
{
    Document *selectedDoc = (Document*)m_window->getTabWidget()->widget(tab);
    if (selectedDoc->close()) {
        // deleteLater also causes the tab to be removed.
        selectedDoc->deleteLater();
    }

    // When the last Document has been closed, create a new one.
    if (m_window->getTabWidget()->count() == 0) {
        newDocument();
    }
}

void MainControl::newDocument()
{
    Document *document = new Document(m_window);
    connect(document, SIGNAL(fileNameChanged(QString,Document*)), this, SLOT(documentNameChanged(QString,Document*)));
    document->addNewPage();
    m_window->getTabWidget()->addTab(document, document->fileName());
}

void MainControl::saveFileAs(const QString &outputFileName)
{
    // TODO: Implement saveFileAs.
    KSaveFile file(outputFileName);
    file.open();/*

    QByteArray outputByteArray;
    outputByteArray.append(textArea->toPlainText().toUtf8());
    file.write(outputByteArray);
    file.finalize();
    file.close()*/;

    //m_fileName = outputFileName;
}

void MainControl::openFile()
{
    // TODO: Implement openFile.
    QString fileNameFromDialog = KFileDialog::getOpenFileName();

    QString tmpFile;
    if (KIO::NetAccess::download(fileNameFromDialog, tmpFile, m_window)) {
        QFile file(tmpFile);
//     file.open(QIODevice::ReadOnly);
//     textArea->setPlainText(QTextStream(&file).readAll());
//      m_fileName = fileNameFromDialog;

        KIO::NetAccess::removeTempFile(tmpFile);
    } else {
        // TODO: Do nothing when the user clicked 'cancel'.
        KMessageBox::error(m_window, KIO::NetAccess::lastErrorString());
    }
}

void MainControl::documentNameChanged(QString newName, Document* source)
{
    int tabIndex = m_window->getTabWidget()->indexOf(source);
    m_window->getTabWidget()->setTabText(tabIndex, newName);
}

void MainControl::redo()
{
    // Do nothing when no document is open.
    Document *currentDoc = (Document*)m_window->getTabWidget()->currentWidget();
    currentDoc->redo();
}

void MainControl::undo()
{
    // Do nothing when no document is open.
    Document *currentDoc = (Document*)m_window->getTabWidget()->currentWidget();
    currentDoc->undo();
}

void MainControl::toolChanged(QAction* action)
{
    Document *doc = currentDoc();

    if (m_window->actionCollection()->action("set-tool-pen") == action) {
        doc->setPenTool();
    } else if (m_window->actionCollection()->action("set-tool-eraser") == action) {
        doc->setEraserTool();
    }
}

void MainControl::penSizeChanged(QAction* action)
{
    Document *doc = currentDoc();
    if (m_window->actionCollection()->action("set-size-small") == action) {
        doc->currentTool()->currentPen()->setWidth(1);
    } else if (m_window->actionCollection()->action("set-size-medium") == action) {
        doc->currentTool()->currentPen()->setWidth(2);
    } else if (m_window->actionCollection()->action("set-size-big") == action) {
        doc->currentTool()->currentPen()->setWidth(3);
    }
}

void MainControl::zoomFit()
{
    Document *doc = currentDoc();
    qreal new_scale = doc->viewport()->height() / doc->currentPage()->realSize().height();
    currentDoc()->setScale(new_scale);
}

void MainControl::zoomIn()
{
    // TODO: Magic number
    if (currentDoc()->scale() > 3) {
        return;
    }
    currentDoc()->setScale(currentDoc()->scale()*1.2);
}

void MainControl::zoomOrig()
{
    currentDoc()->setScale(1);
}

void MainControl::zoomOut()
{
    // TODO: Magic number
    if (currentDoc()->scale() < 0.2) {
        return;
    }
    currentDoc()->setScale(currentDoc()->scale()*0.8);
}

void MainControl::zoomWidth()
{
    Document *doc = currentDoc();
    qreal new_scale = doc->viewport()->width() / doc->currentPage()->realSize().width();
    currentDoc()->setScale(new_scale);
}
